package com.shujia.custom;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.lazy.LazyHiveVarchar;
import org.apache.hadoop.hive.serde2.lazy.LazyInteger;
import org.apache.hadoop.hive.serde2.lazy.LazyPrimitive;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;

/*
        这个方法主要是对自定义的UDF函数进行初始化，目的是指定调用完函数返回的值的类型
        需求：传入一个字符串，返回一个新的字符串
        举例：SMITH --> 数加：SMITH 666
     */
public class UDFDemo2 extends GenericUDF {
    @Override
    public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
        return PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    }

    @Override
    public Object evaluate(DeferredObject[] arguments) throws HiveException {
        DeferredObject argument = arguments[0];
        Object o = argument.get();
//        System.out.println(o.getClass());

        String str = o.getClass().getName();
        if(o!=null){
            // 判断元素类型是否哦是一个字符串类型
            if(o instanceof LazyHiveVarchar){  //对象 instanceof 类型
                str =  "数加："+o+" 666";
            }

            if(o instanceof LazyInteger){
                LazyPrimitive i = (LazyPrimitive) o;
                IntWritable i2 = (IntWritable) i.getWritableObject();
                int i3 = i2.get();
                if(i3==10){
                    str = "部门编号10：ACCOUNTING";
                }else if(i3==20){
                    str = "部门编号20：RESEARCH";
                }else if(i3==30){
                    str = "部门编号30：SALES";
                }else if(i3==40){
                    str = "部门编号40：OPERATIONS";
                }
            }
        }

        return str;
    }

    @Override
    public String getDisplayString(String[] children) {
        return "这是我们自己使用新版本写法自定义的UDF函数";
    }
}
